package com.atguigu.gmall.item.api;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.lock.RedisDistLock;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class LockTestController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedisDistLock redisDistLock;

    @Autowired
    RedissonClient redissonClient;

    //Lock lock = new ReentrantLock();
    int i = 0;

    @GetMapping("/incr")
    public Result increment(){
        //lock.lock();
        String token = redisDistLock.lock();

        System.out.println("a");
        String a = redisTemplate.opsForValue().get("a");

        Long i = Long.parseLong(a);
        i++;
        redisTemplate.opsForValue().set("a",i + "");
        //lock.unlock();
        redisDistLock.unlock(token);
        return Result.ok();
    }

    @GetMapping("/lock/redisson")
    public Result redissonLock() throws InterruptedException {
        //1、得到一把锁
        RLock lock = redissonClient.getLock("hello-lock");
        //2、加锁
        lock.lock();//阻塞式加锁
        //lock.lock(5, TimeUnit.SECONDS);
        //执行业务逻辑
        System.out.println("得到锁");
        Thread.sleep(50000);
        System.out.println("释放锁");
        //3、解锁
        lock.unlock();

        return Result.ok();
    }

    @GetMapping("/rw/writeLock")
    public Result writeLock() throws InterruptedException {
        RReadWriteLock rw = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = rw.writeLock();
        rLock.lock();
        Thread.sleep(10000);
        i = 100;
        rLock.unlock();
        return Result.ok();
    }

    @GetMapping("/rw/readLock")
    public Result readLock(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        System.out.println(i);
        rLock.unlock();
        return Result.ok();
    }

    @GetMapping("/longzhu")
    public Result shouJiLongZhu(){
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("cdl-lock");
        countDownLatch.countDown();
        return Result.ok("收集到一颗龙珠！");
    }

    @GetMapping("/shenlong")
    public Result shenlong() throws InterruptedException {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("cdl-lock");
        countDownLatch.trySetCount(7);
        countDownLatch.await();

        return Result.ok("召唤神龙");
    }
}
